﻿package com.inasryev.luxmeter;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.graphics.Color;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity implements OnInitListener{

	  private TextView textView_current;
	  private TextView textView_min;
	  private TextView textView_max;
	  private TextView caption_curr;
	  private CheckBox checkbox_freeze;
	  private Button   button_reset;
	  private ViewGroup activity_main;
	  int lux_max = 0;
	  int lux_min = 999999;
	  int lux_curr;
	  int timer_interval = 40;
	  Timer myTimer = new Timer(); // create new timer
	  int font_size = 140;
      boolean f_freeze = false;
      boolean f_speak = false;
      boolean f_tts_inited = false;
      int speak_start_interval = 1000*4;
      int speak_interval_tmp = 0;
	  //TTS object
      private TextToSpeech myTTS = null;
	  //status check code
      //private int MY_DATA_CHECK_CODE = 0;
      private static final String TAG = "AndroidRuntime";
	  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //fix screen orientation
        //setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        
        //set music stream for TTS
        setVolumeControlStream(AudioManager.STREAM_MUSIC);
        
        textView_current = (TextView) findViewById(R.id.textView_current);
    	textView_min = (TextView) findViewById(R.id.textView_min);
    	textView_max = (TextView) findViewById(R.id.textView_max);
    	caption_curr = (TextView) findViewById(R.id.caption_curr);
	  	checkbox_freeze = (CheckBox)  findViewById(R.id.checkBox_freeze);
	  	button_reset    = (Button)    findViewById(R.id.button_reset);
	  	activity_main   = (ViewGroup) findViewById(R.id.activity_main);
	  	
        Typeface LCDTypeface = Typeface.createFromAsset(getAssets(), "fonts/SF Digital Readout Medium.ttf");
        
        textView_current.setTypeface(LCDTypeface);
        textView_min.setTypeface(LCDTypeface);
        textView_max.setTypeface(LCDTypeface);
        textView_current.setTextSize(font_size);
        textView_min.setTextSize(font_size-60);
        textView_max.setTextSize(font_size-60);
        
        
    	//check for TTS data
        /*Log.d(TAG, "new Intent()");
        Intent checkTTSIntent = new Intent();
        checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
        Log.d(TAG, "startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE)");
        startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
        */
        myTTS = new TextToSpeech(this, this);
        
    	final Handler uiHandler = new Handler();
    	//start timer
    	myTimer.schedule(new TimerTask() { // describe job
    	    @Override
    	    public void run() {
    	        final String result = GetLightPower();
    	        uiHandler.post(new Runnable() {
    	            @Override
    	            public void run() {
	    	            if(! f_freeze){
		    	            textView_current.setText(result);
	    	            	textView_min.setText( Integer.toString(lux_min) );
	    	            	textView_max.setText( Integer.toString(lux_max) );
	    	            	if(f_speak){
		    	            	speak_interval_tmp += timer_interval;
		    	            	// it's time to speak 
		    	            	if(speak_interval_tmp>=speak_start_interval){
		    	            		speak_interval_tmp = 0;
		    	            		speakWords(result);
		    	            	}
	    	            	}
	    	            }
    	            }
    	        });
    	    };
    	}, 0L, timer_interval); // interval = 40 milliseconds, 0 milliseconds to first launch.    	
    	
    	
    }


    
    /*
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }*/


    public String GetLightPower(){
    	String result = "";
    	String error_text = ""; 
    	try{
            if(! f_freeze){
	    	    Scanner st = new Scanner(new File("/sys/devices/virtual/lightsensor/switch_cmd/lightsensor_file_state"));
	    	    lux_curr = st.nextInt();
	    	    if(lux_curr>lux_max){ lux_max = lux_curr; }
	    	    if(lux_curr<lux_min){ lux_min = lux_curr; }
		    	result = Integer.toString(lux_curr);
	        	st.close();
            }
        	error_text = "";
        	return result;
        } catch (FileNotFoundException e) {
            //e.printStackTrace();
        	error_text = "FileNotFoundException: "+e.toString();
        	ShowError(error_text);
        	return result;
        }
    }
    
    
    // Called when the user clicks the Reset button 
    public void ResetValues(View view) {
  	  lux_max = lux_curr;
  	  lux_min = lux_curr;
    }    
    
    // Called when the user clicks the Freeze button 
    public void FreezeValues(View view) {
    	f_freeze = ! f_freeze;
    	if(f_freeze){
    		activity_main.setBackgroundColor(Color.argb(80, 190, 190, 255));
    		checkbox_freeze.setBackgroundColor(Color.argb(200, 100, 100, 255));
    	}else{
    		activity_main.setBackgroundColor(Color.argb(0, 200, 200, 255));
    		checkbox_freeze.setBackgroundColor(Color.argb(0, 100, 100, 255));
        }
    }    

    // Called when the user clicks the Freeze button 
    public void SetSpeakFlag(View view) {
    	f_speak = ! f_speak;
    	speak_interval_tmp += 2*speak_start_interval;
    }    

    
	//speak the user text
	private void speakWords(String speech) {
			//speak straight away
            //Log.d(TAG, "speakWords speech="+speech);
            if( (f_tts_inited == true ) & ( speech.length()>0 ) ) 
            	myTTS.speak(speech, TextToSpeech.QUEUE_FLUSH, null);
	}

	/*//act on result of TTS data check
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d(TAG, "onActivityResult requestCode=");
		if (requestCode == MY_DATA_CHECK_CODE) {
			if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
			    Log.d(TAG, "resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS");
				//the user has the necessary data - create the TTS
				myTTS = new TextToSpeech(this, this);
			}
			else {
			    Log.d(TAG, "resultCode != TextToSpeech.Engine.CHECK_VOICE_DATA_PASS");
				//no data - install it now
				Intent installTTSIntent = new Intent();
				installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
				startActivity(installTTSIntent);
			}
		}
	}
	*/
		
	//setup TTS
	public void onInit(int initStatus) {
	    Log.d(TAG, "onInit");
			//check for successful instantiation
		if (initStatus == TextToSpeech.SUCCESS) {
		    Log.d(TAG, "initStatus == TextToSpeech.SUCCESS");
		    /*Log.d(TAG, "Locale.getDefault()="+Locale.getDefault());
		    Log.d(TAG, "myTTS.isLanguageAvailable(Locale.getDefault())==" + myTTS.isLanguageAvailable(Locale.getDefault()) );
			if(myTTS.isLanguageAvailable(Locale.getDefault())==TextToSpeech.LANG_AVAILABLE){
			    Log.d(TAG, "isLanguageAvailable(Locale.getDefault())");
				myTTS.setLanguage(Locale.getDefault());
				f_tts_inited = true;
			}else if(myTTS.isLanguageAvailable(Locale.US)==TextToSpeech.LANG_AVAILABLE){
			    Log.d(TAG, "isLanguageAvailable(Locale.US)");
				myTTS.setLanguage(Locale.US);
				f_tts_inited = true;
			}*/	
			f_tts_inited = true;
		}
		else if (initStatus == TextToSpeech.ERROR) {
		    Log.d(TAG, "initStatus == TextToSpeech.ERROR");
			ShowError("Sorry! Text To Speech failed...");
		}
	}

    //@Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //Log.d(TAG, "onKeyDown");
	    //if speaking, use volume buttons for volume
	    if(f_speak){ 
	    	super.onKeyDown(keyCode, event);
	    	if( (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
	    	   |(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
	    	  )  return false;
	    	else return true;
	    }
	    //process only "action_up" action
        if(keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
            checkbox_freeze.performClick();
            return true;
        }else if(keyCode == KeyEvent.KEYCODE_VOLUME_DOWN){
            button_reset.performClick();
            return true;
        }else{
	    	super.onKeyDown(keyCode, event);
        	return true;
        }
    }	

	//freeze all and show error message
	public void ShowError(String err_text){
		f_freeze = true;
		f_speak = false;
		textView_current.setText(err_text);
		caption_curr.setText(err_text);
	}

	
	public void onDestroy() {
		// Don't forget to shutdown!
	    Log.d(TAG, "onDestroy()");
		if (myTTS != null) {
			myTTS.stop();
			myTTS.shutdown();
		}
		super.onDestroy();
	}

	
}
